import { type CSSProperties, FC, memo, useEffect, useRef } from "react";

import styles from "./index.module.scss";

interface IExpandText {
	className?: string;
	style?: CSSProperties;
	textContent: string;
}
const ExpandText: FC<IExpandText> = ({ className, style, textContent }) => {
	const targetEl = useRef<HTMLDivElement | null>(null);
	const inputEl = useRef<HTMLInputElement | null>(null);

	useEffect(() => {
		const el = targetEl.current;
		const initOverflow = () => {
			if (el) {
				const { scrollHeight, offsetHeight } = el;
				el.dataset.overflow = String(scrollHeight > offsetHeight);
				if (inputEl.current) {
					inputEl.current.checked = false;
				}
			}
		};

		const handleAnimationStart = (event: AnimationEvent) => {
			console.log(event, "123");
			if (event.animationName.includes("appear")) {
				initOverflow();
			}
		};

		if (el) {
			el.addEventListener("animationstart", handleAnimationStart);
			window.addEventListener("resize", initOverflow);

			// 清理函数
			return () => {
				el && el.removeEventListener("animationstart", handleAnimationStart);
				window.removeEventListener("resize", initOverflow);
			};
		}
	}, []);

	return (
		<div className={`${styles["container"]} ${className ?? ""}`} style={{ ...(style ?? {}) }}>
			<div className="text-wrap" ref={targetEl}>
				<label className="expand">
					<input type="checkbox" hidden ref={inputEl} />
				</label>
				{textContent ?? ""}
			</div>
		</div>
	);
};

export default memo(ExpandText);
